package com.zelin.page.controller;

import com.alipay.api.AlipayApiException;
import com.zelin.page.service.PayService;
import com.zyg.common.entity.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * ------------------------------
 * 功能：
 * 作者：WF
 * 微信：hbxfwf13590332912
 * 创建时间：2021/11/19-16:30
 * ------------------------------
 */
@RestController
public class PayController {
    @Autowired
    private PayService payService;
    //1. 支付宝发送过来的异步通知
    @PostMapping("/payed/notify")
    public String payNotify(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException {
        System.out.println("vo = " + vo);
        //1. 得到登录用户
        //String userId = SecurityContextHolder.getContext().getAuthentication().getName();
        //2. 得支支付宝后台传入的数据
        Map<String,String> params = new HashMap<>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        String result = payService.payNotify(vo,params);
        System.out.println("result = " + result);
        return result;

    }

    @GetMapping("hello")
    public String hello(){
        return "hello";
    }
}
